<template>
  <div class="shop-cart-container">
    <!-- 导航栏 -->
    <nav class="navbar">
      <div class="navbar-container">
        <div class="logo" @click="goToHome">QingBook</div>
        <ul class="nav-menu">
          <li 
            class="nav-item" 
            :class="{ active: activeIndex === 1 }"
            @click="goToHome"
          >
            首页
          </li>
          <li 
            class="nav-item"
            :class="{ active: activeIndex === 2 }"
            @click="goToOrders"
          >
            订单
          </li>
          <li 
            class="nav-item"
            :class="{ active: activeIndex === 3 }"
          >
            购物车
          </li>
          <li class="nav-item">
            <img class="avatar" :src="user.avatarUrl" alt="用户头像" />
          </li>
        </ul>
      </div>
    </nav>

    <!-- 购物车内容 -->
    <div class="cart-content">
      <div class="cart-header">
        <h2>购物车</h2>
        <div class="cart-stats">
          共 {{ cartItems.length }} 件商品
        </div>
      </div>

      <div class="cart-items">
        <!-- 购物车商品列表 -->
        <div v-for="(item, index) in cartItems" :key="item.id" class="cart-item">
          <div class="item-select">
            <input 
              type="checkbox" 
              :checked="item.selected" 
              @change="toggleItemSelection(index)"
            />
          </div>
          <div class="item-image">
            <img :src="item.image" :alt="item.title" />
          </div>
          <div class="item-details">
            <h3 class="item-name">{{ item.title }}</h3>
            <p class="item-specs">{{ item.specs }}</p>
            <p class="item-color">颜色：{{ item.color }}</p>
          </div>
          <div class="item-price">
            <span class="current-price">¥{{ item.price.toFixed(2) }}</span>
            <span class="original-price" v-if="item.originalPrice">¥{{ item.originalPrice.toFixed(2) }}</span>
          </div>
          <div class="item-quantity">
            <button class="quantity-btn" @click="decreaseQuantity(index)">-</button>
            <input 
              type="number" 
              v-model.number="item.quantity" 
              min="1" 
              class="quantity-input"
              @change="validateQuantity(index)"
            />
            <button class="quantity-btn" @click="increaseQuantity(index)">+</button>
          </div>
          <div class="item-total">
            ¥{{ (item.price * item.quantity).toFixed(2) }}
          </div>
          <div class="item-actions">
            <button class="action-btn" @click="removeItem(index)">删除</button>
            <button class="action-btn">收藏</button>
          </div>
        </div>
      </div>

      <!-- 空购物车提示 -->
      <div class="empty-cart" v-if="cartItems.length === 0">
        <div class="empty-icon">🛒</div>
        <h3>您的购物车是空的</h3>
        <p>快去选购商品吧！</p>
        <button class="go-shopping-btn" @click="goToHome">去购物</button>
      </div>

      <!-- 购物车结算栏 -->
      <div class="cart-footer" v-if="cartItems.length > 0">
        <div class="select-all">
          <input 
            type="checkbox" 
            :checked="allSelected" 
            @change="toggleSelectAll"
          />
          <span>全选</span>
        </div>
        <div class="total-info">
          <div class="total-amount">
            合计：<span class="amount">¥{{ totalAmount.toFixed(2) }}</span>
          </div>
          <div class="saving" v-if="totalSaving > 0">
            已节省：¥{{ totalSaving.toFixed(2) }}
          </div>
        </div>
        <button class="checkout-btn" :disabled="selectedCount === 0" @click="openPaymentModal">
          去结算 ({{ selectedCount }})
        </button>
      </div>
    </div>

    <!-- 支付弹窗 -->
    <div v-if="showPaymentModal" class="modal-overlay" @click="closePaymentModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>确认支付</h3>
          <button class="close-btn" @click="closePaymentModal">×</button>
        </div>
        <div class="modal-body">
          <div class="payment-summary">
            <h4>订单摘要</h4>
            <div class="order-items">
              <div v-for="item in selectedItems" :key="item.id" class="order-item">
                <span class="item-name">{{ item.title }}</span>
                <span class="item-quantity">x{{ item.quantity }}</span>
                <span class="item-price">¥{{ (item.price * item.quantity).toFixed(2) }}</span>
              </div>
            </div>
            <div class="order-total">
              <strong>总计：¥{{ totalAmount.toFixed(2) }}</strong>
            </div>
          </div>
          
          <div class="payment-methods">
            <h4>选择支付方式</h4>
            <div class="payment-options">
              <label class="payment-option">
                <input type="radio" v-model="selectedPayment" value="alipay" />
                <span class="payment-icon">支付宝</span>
              </label>
              <label class="payment-option">
                <input type="radio" v-model="selectedPayment" value="wechat" />
                <span class="payment-icon">微信支付</span>
              </label>
              <label class="payment-option">
                <input type="radio" v-model="selectedPayment" value="bank" />
                <span class="payment-icon">银行卡</span>
              </label>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="closePaymentModal">取消</button>
          <button class="confirm-pay-btn" @click="processPayment" :disabled="!selectedPayment">
            确认支付
          </button>
        </div>
      </div>
    </div>

    <!-- 支付成功弹窗 -->
    <div v-if="showSuccessModal" class="modal-overlay success-overlay">
      <div class="modal-content success-content">
        <div class="success-icon">✓</div>
        <h3>支付成功！</h3>
        <p>订单已生成，我们将尽快为您发货</p>
        <div class="success-actions">
          <button class="view-orders-btn" @click="goToOrders">查看订单</button>
          <button class="continue-shopping-btn" @click="continueShopping">继续购物</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/store/auth'
import { 
  HomeIcon, SearchIcon, PlusCircleIcon, 
  MessageCircleIcon, UserIcon, SettingsIcon 
} from 'lucide-vue-next'

const router = useRouter()
const authStore = useAuthStore()

// 用户信息
const user = ref(authStore.user || {
  name: '用户',
  username: 'username',
  avatar: 'https://via.placeholder.com/40'
})

// 响应式数据
const activeIndex = ref(3)
const headerImage = ref('src/assets/header.png')
const cartItems = ref([])
const showPaymentModal = ref(false)
const showSuccessModal = ref(false)
const selectedPayment = ref('')
const isLoading = ref(false)

// 计算属性
const allSelected = computed(() => {
  return cartItems.value.length > 0 && cartItems.value.every(item => item.selected)
})

const selectedCount = computed(() => {
  return cartItems.value.filter(item => item.selected).length
})

const totalAmount = computed(() => {
  return cartItems.value
    .filter(item => item.selected)
    .reduce((total, item) => total + item.price * item.quantity, 0)
})

const totalSaving = computed(() => {
  return cartItems.value
    .filter(item => item.selected && item.originalPrice)
    .reduce((total, item) => total + (item.originalPrice - item.price) * item.quantity, 0)
})

const selectedItems = computed(() => {
  return cartItems.value.filter(item => item.selected)
})

// 生命周期
onMounted(() => {
  const savedCart = localStorage.getItem('qingbook-cart')
  if (savedCart) {
    const parsedCart = JSON.parse(savedCart)
    cartItems.value = parsedCart.map(item => ({
      ...item,
      price: Number(item.price),
      originalPrice: item.originalPrice ? Number(item.originalPrice) : null,
      quantity: Number(item.quantity) || 1
    }))
  }
})

// 方法
const goToHome = () => {
  router.push('/shop')
}

const goToOrders = () => {
  router.push('/shoporder')
}

const toggleItemSelection = (index) => {
  cartItems.value[index].selected = !cartItems.value[index].selected
  saveCartToLocalStorage()
}

const toggleSelectAll = () => {
  const selectAll = !allSelected.value
  cartItems.value.forEach(item => {
    item.selected = selectAll
  })
  saveCartToLocalStorage()
}

const increaseQuantity = (index) => {
  cartItems.value[index].quantity++
  saveCartToLocalStorage()
}

const decreaseQuantity = (index) => {
  if (cartItems.value[index].quantity > 1) {
    cartItems.value[index].quantity--
    saveCartToLocalStorage()
  }
}

const validateQuantity = (index) => {
  if (cartItems.value[index].quantity < 1) {
    cartItems.value[index].quantity = 1
    saveCartToLocalStorage()
  }
}

const removeItem = (index) => {
  cartItems.value.splice(index, 1)
  saveCartToLocalStorage()
}

const saveCartToLocalStorage = () => {
  localStorage.setItem('qingbook-cart', JSON.stringify(cartItems.value))
}

const openPaymentModal = () => {
  if (selectedCount.value === 0) return
  showPaymentModal.value = true
  selectedPayment.value = 'alipay'
}

const closePaymentModal = () => {
  showPaymentModal.value = false
  selectedPayment.value = ''
}

const processPayment = async () => {
  if (!selectedPayment.value) return
  
  isLoading.value = true
  
  try {
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    const selected = selectedItems.value
    if (selected.length === 0) {
      throw new Error('没有选中的商品')
    }
    
    const totalAmountValue = selected.reduce((total, item) => {
      return total + (item.price * item.quantity)
    }, 0)
    
    const newOrder = {
      id: 'ORDER_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9),
      createTime: new Date().getTime(),
      status: 'pending_shipment',
      shopName: 'QingBook官方旗舰店',
      items: selected.map(item => ({
        id: item.id,
        title: item.title,
        image: item.image,
        specs: item.specs,
        color: item.color,
        price: item.price,
        quantity: item.quantity
      })),
      totalAmount: totalAmountValue,
      expressInfo: null
    }
    
    const savedOrders = localStorage.getItem('qingbook-orders')
    const existingOrders = savedOrders ? JSON.parse(savedOrders) : []
    existingOrders.unshift(newOrder)
    localStorage.setItem('qingbook-orders', JSON.stringify(existingOrders))
    
    showPaymentModal.value = false
    showSuccessModal.value = true
    cartItems.value = cartItems.value.filter(item => !item.selected)
    saveCartToLocalStorage()
    
  } catch (error) {
    console.error('支付失败:', error)
    alert('支付失败，请重试')
  } finally {
    isLoading.value = false
  }
}

const continueShopping = () => {
  showSuccessModal.value = false
  goToHome()
}
</script>

<style scoped>
.shop-cart-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.navbar {
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  padding: 0 20px;
  position: sticky;
  top: 0;
  z-index: 100;
}

.navbar-container {
  display: flex;
  align-items: center;
  max-width: 1200px;
  margin: 0 auto;
  height: 60px;
}

.logo {
  font-size: 20px;
  font-weight: bold;
  color: #00b4ac;
  margin-right: auto;
  padding: 0 15px;
  cursor: pointer;
  user-select: none;
}

.nav-menu {
  display: flex;
  list-style: none;
  height: 100%;
}

.nav-item {
  display: flex;
  align-items: center;
  padding: 0 15px;
  cursor: pointer;
  height: 100%;
  transition: all 0.3s ease;
  position: relative;
}

.nav-item:hover {
  color: #00b4ac;
  background-color: rgba(0, 180, 172, 0.1);
}

.nav-item.active {
  color: #00b4ac;
  border-bottom: 2px solid #00b4ac;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.cart-content {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
}

.cart-header {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.cart-header h2 {
  margin: 0;
  color: #333;
}

.cart-stats {
  font-size: 14px;
  color: #666;
}

.cart-items {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.cart-item {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 20px;
}

.item-select {
  display: flex;
  align-items: center;
}

.item-select input {
  width: 18px;
  height: 18px;
  cursor: pointer;
}

.item-image {
  width: 80px;
  height: 80px;
  border-radius: 6px;
  overflow: hidden;
}

.item-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.item-details {
  flex: 1;
}

.item-name {
  margin: 0 0 8px 0;
  font-size: 16px;
  color: #333;
}

.item-specs, .item-color {
  margin: 0 0 5px 0;
  font-size: 14px;
  color: #666;
}

.item-price {
  min-width: 120px;
  text-align: right;
}

.current-price {
  font-size: 16px;
  font-weight: bold;
  color: #ff6b6b;
  margin-right: 8px;
}

.original-price {
  font-size: 14px;
  color: #999;
  text-decoration: line-through;
}

.item-quantity {
  display: flex;
  align-items: center;
  gap: 8px;
}

.quantity-btn {
  width: 30px;
  height: 30px;
  border: 1px solid #ddd;
  background-color: #fff;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.quantity-btn:hover {
  background-color: #f5f5f5;
}

.quantity-input {
  width: 60px;
  height: 30px;
  border: 1px solid #ddd;
  border-radius: 4px;
  padding: 0 8px;
  font-size: 14px;
  text-align: center;
}

.item-total {
  min-width: 100px;
  text-align: right;
  font-size: 16px;
  font-weight: bold;
  color: #ff6b6b;
}

.item-actions {
  display: flex;
  gap: 10px;
}

.action-btn {
  padding: 6px 12px;
  border: 1px solid #ddd;
  background-color: #fff;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
}

.action-btn:hover {
  opacity: 0.8;
}

.empty-cart {
  text-align: center;
  padding: 60px 20px;
  background-color: #fff;
  border-radius: 8px;
}

.empty-icon {
  font-size: 80px;
  margin-bottom: 20px;
  color: #ccc;
}

.empty-cart h3 {
  margin: 0 0 10px 0;
  color: #333;
}

.empty-cart p {
  color: #666;
  margin-bottom: 30px;
}

.go-shopping-btn {
  padding: 12px 30px;
  background-color: #00b4ac;
  color: #fff;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.go-shopping-btn:hover {
  background-color: #00857d;
}

.cart-footer {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.select-all {
  display: flex;
  align-items: center;
  gap: 8px;
}

.select-all input {
  width: 18px;
  height: 18px;
  cursor: pointer;
}

.total-info {
  text-align: right;
  flex: 1;
}

.total-amount {
  font-size: 16px;
  margin-bottom: 8px;
}

.amount {
  font-weight: bold;
  color: #ff6b6b;
  font-size: 18px;
}

.saving {
  font-size: 14px;
  color: #4caf50;
}

.checkout-btn {
  padding: 12px 30px;
  background-color: #00b4ac;
  color: #fff;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s;
  margin-left: 20px;
}

.checkout-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background-color: #fff;
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.modal-header h3 {
  margin: 0;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
}

.close-btn:hover {
  color: #666;
}

.modal-body {
  padding: 20px;
}

.payment-summary {
  margin-bottom: 20px;
}

.payment-summary h4 {
  margin: 0 0 15px 0;
  color: #333;
}

.order-items {
  margin-bottom: 15px;
}

.order-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f5f5f5;
}

.order-item:last-child {
  border-bottom: none;
}

.order-item .item-name {
  flex: 1;
  margin: 0;
}

.order-item .item-quantity {
  margin: 0 15px;
  color: #666;
}

.order-item .item-price {
  margin: 0;
  min-width: auto;
  font-size: 16px;
}

.order-total {
  text-align: right;
  padding: 10px 0;
}

.order-total strong {
  font-size: 18px;
}

.payment-methods {
  margin-top: 20px;
}

.payment-methods h4 {
  margin: 0 0 15px 0;
  color: #333;
}

.payment-options {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.payment-option {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.payment-option:hover {
  border-color: #00b4ac;
  background-color: rgba(0, 180, 172, 0.05);
}

.payment-icon {
  font-size: 20px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 20px;
  border-top: 1px solid #eee;
}

.cancel-btn {
  padding: 10px 20px;
  border: 1px solid #ddd;
  background-color: #fff;
  color: #666;
  border-radius: 4px;
  cursor: pointer;
}

.confirm-pay-btn {
  padding: 10px 20px;
  background-color: #00b4ac;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.confirm-pay-btn:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.success-overlay {
  background-color: rgba(0, 0, 0, 0.5);
}

.success-content {
  background-color: #fff;
  border-radius: 8px;
  padding: 40px 20px;
  text-align: center;
}

.success-icon {
  font-size: 60px;
  color: #4caf50;
  margin-bottom: 20px;
}

.success-content h3 {
  margin: 0 0 15px 0;
  color: #333;
}

.success-content p {
  color: #666;
  margin-bottom: 30px;
}

.success-actions {
  display: flex;
  gap: 15px;
  justify-content: center;
}

.view-orders-btn, .continue-shopping-btn {
  padding: 12px 30px;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.view-orders-btn {
  background-color: #00b4ac;
  color: #fff;
}

.continue-shopping-btn {
  background-color: #fff;
  color: #00b4ac;
  border: 1px solid #00b4ac;
}

.view-orders-btn:hover {
  background-color: #00857d;
}

.continue-shopping-btn:hover {
  background-color: #f5f5f5;
}

@media (max-width: 768px) {
  .cart-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .item-image {
    width: 100%;
    height: auto;
  }

  .item-quantity {
    width: 100%;
    justify-content: flex-end;
  }

  .item-total {
    width: 100%;
    text-align: right;
  }

  .item-actions {
    width: 100%;
    justify-content: flex-end;
  }

  .cart-footer {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .total-info {
    text-align: left;
  }

  .checkout-btn {
    margin-left: 0;
    width: 100%;
  }
}
</style>